package org.example.MQ;

import java.sql.SQLOutput;
import java.util.Date;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Producer implements Runnable {

    //共享缓冲区
    private BlockingQueue<Data> queue;

    //多线程间是否启动变量，强制在组内存中刷新
    private volatile  boolean isRunning = true;

    //id生成
    private static AtomicInteger count = new AtomicInteger();

    public Producer(BlockingQueue<Data> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (isRunning){
            //获取数据进行累加
            try {
                //取数据随机消耗
                TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextInt(1000));
                //id递增
                int id = count.incrementAndGet();

                Data data = new Data(id,"数据:"+id);
                System.out.println("当前生成线程："+Thread.currentThread().getName()
                +"获取了数据，数据id："+id+"。进行装载到公共缓存区");
                if (!this.queue.offer(data,2,TimeUnit.SECONDS)){
                    System.out.println("提交缓冲区数据失败");
                }

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public  void isStop(){
        this.isRunning = false;
    }
}
